package com.wcdxg.flow

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * Created by ZhouHanJun.
 * on 2021/12/23
 */
class MainViewModel : ViewModel() {

    private var _uiState: MutableStateFlow<String> = MutableStateFlow("")
    val uiState = _uiState

    //黏性事件 可以缓存发射值
    private val _eventFlow = MutableSharedFlow<String>(replay = 30)
    val eventFlow = _eventFlow

    val liveDataState = MutableLiveData<String>()

    init {
        //模拟网络延时
//        viewModelScope.launch {
//            (1..20).asFlow()
//                .collect {
//                    Log.e(TAG, "init: $it")
//                    _uiState.value = it.toString()
//                    _eventFlow.emit(it.toString())
//                    delay(300)
//                }
//        }
    }


    fun getNetData(): Flow<String> {
        Log.e(TAG, "getNetData: 获取网络数据")
        //模拟网络延时
        return mockNet()
    }

    private fun mockNet(): Flow<String> {
        return (1..20).asFlow()
            .map {
                it.toString()
            }
            .onEach {
                Log.e(TAG, "mockNet: $it")
                delay(500)
            }
    }
}